﻿
CREATE PROCEDURE [dbo].[CashRegisterDocInsert]
(--кассовый чек (розничная продажа)
	@DocDate smalldatetime,
	@DocNumber int,						--номер чека
	@CashRegisterShiftId int,
	@DepartmentUserId int,
	@SaleDiscountTypesId int, --тип скидки
	@СashlessPayment bit,			--признак безналичной оплаты 0-наличная, 1-безналичная
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @strDocNumber varchar(20), @intCashRegisterId int
DECLARE @intNextId int
	SET NOCOUNT ON

IF (@DocDate Is Null) OR (@CashRegisterShiftId Is Null) OR (@СashlessPayment Is Null)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF @DepartmentUserId Is Null
	SELECT @DepartmentUserId = Id FROM CD.DepartmentUsers WHERE Login = suser_sname()

IF (@DepartmentUserId Is Null)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 2, @strMsg = 'Не указан идентификатор кассира!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF (@SaleDiscountTypesId Is Not Null)
BEGIN
	IF NOT EXISTS (SELECT * FROM CO.SaleDiscountTypes WHERE ID = @SaleDiscountTypesId AND ToDelete = 0)
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		SELECT @intErrCode = 3, 
		@strMsg = 'Отсутствует тип скидки с идентификатором ' + cast(@SaleDiscountTypesId as varchar(20)) + ' !'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END
END

EXEC @intRet = dbo.CheckCashRegisterShift @CashRegisterShiftId, @intCashRegisterId OUTPUT
IF @intRet <> 0 RETURN @intRet

--TODO проработать систему нумерации чеков
IF @DocNumber Is Null
BEGIN
	UPDATE CD.CashRegisters SET @intRet = NextDocNumber, 
	NextDocNumber = @intRet + 1
	WHERE Id = @intCashRegisterId
END ELSE BEGIN
	UPDATE CD.CashRegisters SET @intRet = @DocNumber, 
	NextDocNumber = @DocNumber + 1
	WHERE Id = @intCashRegisterId
END

SET @strDocNumber = cast(@intRet as varchar(20))

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Documents', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CA].[Documents] (Id, [DocTypeId], [DocDate], [DocNumber], 
[ContragentId], CashRegisterShiftId, DepartmentUserId, СashlessPayment, ShiftDepartmentId,
[Note], [MD], [MW]) 
VALUES (@intNextId, 3, @DocDate, @strDocNumber, 
2, @CashRegisterShiftId, @DepartmentUserId, @СashlessPayment, @SaleDiscountTypesId, 
@Note, @MD, @MW);
	
SELECT Id, DepartmentId, DocTypeId, DocDate, DocNumber, 
ContragentId, CashRegisterShiftId, DepartmentUserId, DepartmentId, 
СashlessPayment, ShiftDepartmentId AS SaleDiscountTypesId,
Note, MD, MW 
FROM CA.Documents WHERE (Id = @intNextId)

RETURN 0
